import React, {useState, useEffect } from 'react';
import {connect} from 'react-redux';
import {Row, Col, Table, Button, Modal, Form, Input, message} from 'antd';

import {defaultPagination, TableBtn } from '../publicComponents';
import {get, post} from "../../../utils";
import {mUrl, mTitle} from "../../../config";
import {PlusOutlined} from "@ant-design/icons";

const Page = () => {
    const [form] = Form.useForm();
    const [oneTableData, setOneTableData] = useState([]); // 第一个表格数据
    const [twoTableData, setTwoTableData] = useState([]); // 第二个表格数据
    const [visible, setVisible] = useState(false); // 添加分类的弹框
    const [oneOrTwo, setOneOrTwo] = useState(undefined);
    const [parentid, setParentId] = useState('');
    const [selectRecord, setSelectRecord] = useState({});
    const [pagination, setPagination] = useState(Object.assign({}, defaultPagination)); // 表格分页
    
    // 一级分类表格
    const oneColumn = [
        {
            title: '序号',
            width: 100,
            align: 'center',
            key: 'classifyid',
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '一级分类',
            dataIndex: 'name',
            align: 'center'
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 100,
            align: 'center'
        },
        {
            title: '操作',
            width: 150,
            align: 'center',
            render: (data) => {
                return (
                    <TableBtn
                        onClick={handleBtnClick}
                        record={data}
                        btns={[
                            {id: 1, name: '修改'},
                            {id: 2, name: '删除'},
                            {id: 3, name: data.state === 1 ? '停用' : '启用'}
                        ]}
                    />
                );
            }
        },
    ];

    const twoColumns = [
        {
            title: '序号',
            width: 100,
            align: 'center',
            key: 'classifyid',
            render: (text, record, index) => index + 1
        },
        {
            title: '二级分类',
            dataIndex: 'name',
            align: 'center'
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: 100,
            align: 'center'
        },
        {
            title: '操作',
            width: 150,
            align: 'center',
            render: (data) => {
                return (
                    <TableBtn
                        record={data}
                        onClick={handleBtnClick}
                        btns={[
                            {id: 1, name: '修改'},
                            {id: 2, name: '删除'},
                            {id: 3, name: data.state === 1 ? '停用' : '启用'}
                        ]}
                    />
                );
            }
        },
    ];

    useEffect(() => {
        searchTypeList();
    }, []);
    
    // 加载所有分类列表
    const searchTypeList = (parentid) => {
        get(mUrl.searchAllClassify, {}).then((res) => {
            if (res.state === 1) {
                setOneTableData(res.data);
                if (res.data.length > 0) {
                    let index = 0;
                    if (parentid) {
                        index = res.data.findIndex((item) => item.classifyid === parentid);
                    }
                    setParentId(res.data[index].classifyid);
                    //setTwoTableData(res.data[index].subClassifyList);
                }
            } else {
                message.error(res.showmsg);
            }
        });
    };
    
    const handleBtnClick = (key, record) => {
        switch (key) {
            case 1:
                form.setFieldsValue({
                    name: record.name, sort: record.sort
                });
                if (record.parentid) {
                    setOneOrTwo(2);
                } else {
                    setOneOrTwo(1);
                }
                setSelectRecord(record);
                setVisible(true);
                break;
            case 2:
                Modal.confirm({
                    title: mTitle.typeDelete,
                    onOk: async () => {
                        record.state = -2;
                        const {state, showmsg} = await handleUpdate(record);
                        if (state === 1) {
                            searchTypeList(parentid);
                            message.success("删除成功");
                        } else {
                            message.error(showmsg);
                        }
                    }
                });
                break;
            case 3:
                Modal.confirm({
                    title: (record.state === 1 ? '停用' : '启用') + '该分类?',
                    onOk: async () => {
                        record.state = record.state === 1 ? -1 : 1;
                        const {state, showmsg} = await handleUpdate(record);
                        if (state === 1) {
                            searchTypeList(parentid);
                            message.success((record.state === -1 ? '停用' : '启用') + "成功");
                        } else {
                            message.error(showmsg);
                        }
                    }
                });
                break;
            default:
        }
    };

    const handleUpdate= async (data) => {
        return await post(mUrl.updateClassify, data);
    };

    const onSubmitBack = () => {
        setVisible(false);
        form.resetFields();
        searchTypeList(parentid);
    };

    const tableOnChange = (values)=>{
        setPagination({
            ...pagination,
            current:values.current,
            pageSize: values.pageSize
        });
    };
    
    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>厂家管理 / 分类管理</p></label>
            <Row justify='space-between'>
                <Col span={16}>
                    <div style={{marginBottom: 10}}>
                        <Button
                            type='primary'
                            onClick={() => {
                                setOneOrTwo(1);
                                setSelectRecord(undefined);
                                form.setFieldsValue({
                                    sort: oneTableData.length + 1
                                });
                                setVisible(true);
                            }}
                        >
                            <PlusOutlined/>新增分类
                        </Button>
                    </div>
                    <Table
                        columns={oneColumn}
                        dataSource={oneTableData}
                        bordered
                        rowClassName={(record) => {
                            if (record.classifyid === parentid) {
                                return 'table-select-type';
                            } else {
                                return 'table-type';
                            }
                        }}
                        onRow={record => {
                            return {
                                onClick: event => {
                                    setParentId(record.classifyid);
                                    if (record.subClassifyList) {
                                        setTwoTableData(record.subClassifyList);
                                    } else {
                                        setTwoTableData([]);
                                    }
                                },
                            };
                        }}
                        onChange={tableOnChange}
                        rowKey='classifyid'
                        size='small'
                        pagination={pagination}
                    />
                </Col>
                {/*<Col span={11}>*/}
                {/*    <Button*/}
                {/*        size='small'*/}
                {/*        type='primary'*/}
                {/*        onClick={() => {*/}
                {/*            setOneOrTwo(2);*/}
                {/*            setSelectRecord(undefined);*/}
                {/*            form.setFieldsValue({*/}
                {/*                sort: twoTableData.length + 1*/}
                {/*            });*/}
                {/*            setVisible(true);*/}
                {/*        }}*/}
                {/*    >新增分类</Button>*/}
                {/*    <h6></h6>*/}
                {/*    <Table*/}
                {/*        columns={twoColumns}*/}
                {/*        dataSource={twoTableData}*/}
                {/*        bordered*/}
                {/*        rowKey='classifyid'*/}
                {/*        size='small'*/}
                {/*        pagination={pagination}*/}
                {/*    />*/}
                {/*</Col>*/}
            </Row>
            <CModal
                form={form}
                oneOrTwo={oneOrTwo}
                parentid={parentid}
                visible={visible}
                oneTableData = {oneTableData}
                setOneTableData = {setOneTableData}
                selectRecord={selectRecord}
                setVisible={setVisible}
                onSubmit={onSubmitBack}
            />
        </div>
    );
};


const CModal = ({visible, setVisible, oneOrTwo, selectRecord = {}, parentid, onSubmit, form, oneTableData,setOneTableData}) => {
    const onFinish = (values) => {
        let lastRecord = {};
        let values1 = {}; 
        if (selectRecord.classifyid) {
            // 修改分类
            oneTableData.forEach((item)=>{
                if(Number(values.sort) === item.sort){
                    console.log(item);
                    console.log(selectRecord);
                    values1.sort = selectRecord.sort;
                    values1.name = selectRecord.name;
                    // values1.classifyid = item.classifyid;
                    // values1.level = 1;
                }
            });
            post(mUrl.updateClassify, {...selectRecord, ...values}).then((res) => {
                if (res.state === 1) {
                    onSubmit();
                } else {
                    message.error(res.showmsg);
                }
            });
            // post(mUrl.updateClassify, {...values1}).then((res) => {
            //     if (res.state === 1) {
            //         onSubmit();
            //     } else {
            //         message.error(res.showmsg);
            //     }
            // });
        } else {
            // 增加分类
            values.level = 1;
            if (oneOrTwo === 2) {
                values.parentid = parentid;
                values.level = 2;
            }
            post(mUrl.addClassify, values).then((res) => {
                if (res.state === 1) {
                    onSubmit();
                } else {
                    message.error(res.showmsg);
                }
            });
        }
    };

    useEffect(() => {
        if (!visible) {
            form.resetFields();
        }
    }, [visible,oneTableData]);
    
    return (
        <Modal
            getContainer={false}
            title={selectRecord.classifyid ? '修改分类' : '新增分类'}
            visible={visible}
            onCancel={_ => setVisible(false)}
            footer={null}
        >
            <Form form={form} onFinish={onFinish}>
                <Form.Item
                    label={oneOrTwo === 1 ? '一级分类名称' : '二级分类名称'}
                    rules={[{required: true, message: '请输入分类名称'}]}
                    labelCol={{span: 6}}
                    name='name'
                >
                    <Input/>
                </Form.Item>
                <Form.Item
                    label='排序'
                    rules={[{required: true, message: '请输入排序号'}]}
                    labelCol={{span: 6}}
                    name='sort'
                >
                    <Input/>
                </Form.Item>
                <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                    <Button
                        htmlType="submit" type={'primary'}
                    >提交</Button>
                    <Button style={{marginLeft: 15}}
                            onClick={_ => setVisible(false)}
                    >取消</Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default connect()(Page);